/*
 * @desc 对话框
 * */
define(['jquery'], function($) {

	var dialoger = {
		//对话框
		dialog : function(options){
			if(options.popup){
				this.popup(options);
				return;
			}
			options = $.extend({
				okHandler : options.okHandler || function(){},
				clHandler : options.clHandler || function(){}
			}, options);
			var d = dialog(options);
			d.show();

			return d;
		},

		//元素弹出
		popup : function(options){
			var $el = $(options.el),
				style = this.getCVStyle($el, options);
			$el.css(style);
			if(options.backdrop !== false){
				$modal = (options.modalEl ? $(options.modalEl) : $('<div class="modal-mask"></div>')).appendTo(options.conainerEl || 'body');
				$modal.css(this.getModalStyle($modal, options));
				if(options.backhide){
					$modal.click(function(){
						close();
					});
				}
			}

			//事件
			if(options.closeEl){
				var $close = $(options.closeEl);
				$close.click(function(){
					close();
				});
			}

			//关闭
			function close(){
				$el.fadeOut(function(){
					if(options.destroyAble){
						$el.remove();
						if($modal){
							$modal.remove();
						}
					}
				});
				if($modal){
					$modal.hide();
				}
			}

			$el.fadeIn();

			return {
				//关闭
				close : function(){
					$el.hide();
					$modal.hide();
					return this;
				},

				//删除
				remove : function(){
					$el.remove();
					$modal.remove();
				}
			};
		},

		//警告框
		alert : function(options){
			options = options || {};
			options = $.extend({
				title : options.title,
				msg : options.msg || '提示',
				okHandler : options.okHandler || function(){},
				okClose : true,
				clHandler : null
			}, options, {clHandler : null});
			return this.dialog(options);
		},

		//选择框
		confirm : function(options){
			options = options || {};
			options = $.extend({
				title : options.title,
				msg : options.msg || '选择',
				callback : options.callback,
				okHandler : options.okHandler || function(){},
				okClose : true,
				clHandler : options.clHandler || function(){}
			}, options);
			return this.dialog(options);
		},

		//普通信息展示
		info : function(options){
			options = options || {};
			options = $.extend({
				title : options.title || false,
				msg : options.msg || '提示',
				skin : 'ui-dialog-info',
				timeHidden : options.timeHidden || 3000,
				backdrop : false,
				okHandler : null,
				clHandler : null
			}, options);
			return this.dialog(options);
		},

		//成功信息展示
		success : function(options){
			options = options || {};
			options = $.extend({
				title : options.title || false,
				msg : options.msg || '成功',
				skin : 'ui-dialog-success',
				timeHidden : options.timeHidden || 3000,
				backdrop : false,
				okHandler : null,
				clHandler : null
			}, options);
			return this.dialog(options);
		},

		//警告信息展示
		warning : function(options){
			options = options || {};
			options = $.extend({
				title : options.title || false,
				msg : options.msg || '警告',
				skin : 'ui-dialog-warning',
				timeHidden : options.timeHidden || 3000,
				backdrop : false,
				okHandler : null,
				clHandler : null
			}, options);
			return this.dialog(options);
		},

		//错误信息展示
		error : function(options){
			options = options || {};
			options = $.extend({
				title : options.title || false,
				msg : options.msg || '错误',
				skin : 'ui-dialog-error',
				timeHidden : options.timeHidden || 3000,
				backdrop : false,
				okHandler : null,
				clHandler : null
			}, options);
			return this.dialog(options);
		},

		//隐藏
		hide : function($el){
			if(typeof $el == 'object' && $el){
				if($el.modal) $el.modal('hide');
			}
		},

		//获取水平垂直居中样式
		getCVStyle : function($popup, options){
			options = options || {};
			var $win = $(options.conainerEl || options.window || window),
				width = $win.width(),
				height = $win.height(),
				popWidth = options.width || $popup.width(),
				popHeight = options.height || $popup.height(),
				defaults = {
					width : width * 0.9,
					height : height * 0.9
				}, style;

			if(popWidth < 20 || popWidth > width){
				popWidth = defaults.width;
			}
			if(popHeight < 20 || popHeight > height){
				popHeight = defaults.height;
			}

			style = {
				width : popWidth,
				height : popHeight,
				left : (width - popWidth) / 2,
				top : (height - popHeight) / 2,
				position : 'fixed'/*,
				 'z-index' : options.zindex || 20*/
			};

			return style;
		},

		//获取模态样式
		getModalStyle : function($modal, options){
			options = options || {};
			var $win = $(options.conainerEl || options.window || window),
				width = $win.width(),
				height = $win.height(), style;
			style = {
				position : 'fixed',
				left : 0,
				right : 0,
				top : 0,
				bottom : 0,
				background : '#000',
				opacity : 0.5,
				filter : 'alpha(opacity=50)'/*,
				 'z-index' : options.modalZindex || 10*/
			};

			return style;
		}
	};

	/*!
	 * Popup
	 */
	var Popup =  (function () {
			var _count = 0;
			var _isIE6 = !('minWidth' in $('html')[0].style);
			var _isFixed = !_isIE6;

			function Popup () {

				this.destroyed = false;


				this.__popup = $('<div />')
				/*使用 <dialog /> 元素可能导致 z-index 永远置顶的问题(chrome)*/
					.css({
						display: 'none',
						position: 'absolute',
						/*
						 left: 0,
						 top: 0,
						 bottom: 'auto',
						 right: 'auto',
						 margin: 0,
						 padding: 0,
						 border: '0 none',
						 background: 'transparent'
						 */
						outline: 0
					})
					.attr('tabindex', '-1')
					.html(this.innerHTML)
					.appendTo('body');


				this.__backdrop = this.__mask = $('<div />')
					.css({
						opacity: .7,
						background: '#000'
					});


				// 使用 HTMLElement 作为外部接口使用，而不是 jquery 对象
				// 统一的接口利于未来 Popup 移植到其他 DOM 库中
				this.node = this.__popup[0];
				this.backdrop = this.__backdrop[0];

				_count ++;
			}

			$.extend(Popup.prototype, {

				/**
				 * 初始化完毕事件，在 show()、showModal() 执行
				 * @name Popup.prototype.onshow
				 * @event
				 */

				/**
				 * 关闭事件，在 close() 执行
				 * @name Popup.prototype.onclose
				 * @event
				 */

				/**
				 * 销毁前事件，在 remove() 前执行
				 * @name Popup.prototype.onbeforeremove
				 * @event
				 */

				/**
				 * 销毁事件，在 remove() 执行
				 * @name Popup.prototype.onremove
				 * @event
				 */

				/**
				 * 重置事件，在 reset() 执行
				 * @name Popup.prototype.onreset
				 * @event
				 */

				/**
				 * 焦点事件，在 foucs() 执行
				 * @name Popup.prototype.onfocus
				 * @event
				 */

				/**
				 * 失焦事件，在 blur() 执行
				 * @name Popup.prototype.onblur
				 * @event
				 */

				/** 浮层 DOM 素节点[*] */
				node: null,

				/** 遮罩 DOM 节点[*] */
				backdrop: null,

				/** 是否开启固定定位[*] */
				fixed: false,

				/** 判断对话框是否删除[*] */
				destroyed: true,

				/** 判断对话框是否显示 */
				open: false,

				/** close 返回值 */
				returnValue: '',

				/** 是否自动聚焦 */
				autofocus: true,

				/** 对齐方式[*] */
				align: 'bottom left',

				/** 内部的 HTML 字符串 */
				innerHTML: '',

				/** CSS 类名 */
				className: 'ui-popup',

				/**
				 * 显示浮层
				 * @param   {HTMLElement, Event}  指定位置（可选）
				 */
				show: function (anchor) {

					if (this.destroyed) {
						return this;
					}

					var that = this;
					var popup = this.__popup;
					var backdrop = this.__backdrop;

					this.__activeElement = this.__getActive();

					this.open = true;
					this.follow = anchor || this.follow;


					// 初始化 show 方法
					if (!this.__ready) {

						popup
							.addClass(this.className).addClass('modal-dialoger')
							.attr('role', this.backdrop ? 'alertdialog' : 'dialog')
							.css('position', this.fixed ? 'fixed' : 'absolute');

						if (!_isIE6) {
							$(window).on('resize', $.proxy(this.reset, this));
						}

						popup.modal = function(method){
							if(method == 'hide'){
								that.close().remove();
							}
						};

						// 模态浮层的遮罩
						if (this.backdrop) {
							var backdropCss = {
								position: 'fixed',
								left: 0,
								top: 0,
								width: '100%',
								height: '100%',
								overflow: 'hidden',
								userSelect: 'none',
								zIndex: this.zIndex || Popup.zIndex
							};


							popup.addClass(this.className + '-modal');


							if (!_isFixed) {
								$.extend(backdropCss, {
									position: 'absolute',
									width: $(window).width() + 'px',
									height: $(document).height() + 'px'
								});
							}


							backdrop
								.css(backdropCss)
								.attr({tabindex: '0'})
								.on('focus', $.proxy(this.focus, this));

							// 锁定 tab 的焦点操作
							this.__mask = backdrop
								.clone(true)
								.attr('style', '')
								.insertAfter(popup);

							backdrop
								.addClass(this.className + '-backdrop')
								.insertBefore(popup);

							this.__ready = true;
						}


						if (!popup.html()) {
							popup.html(this.innerHTML);
						}
					}


					popup
						.addClass(this.className + '-show')
						.show();

					backdrop.show();


					this.reset().focus();
					this.__dispatchEvent('show');

					return this;
				},


				/** 显示模态浮层。参数参见 show() */
				showModal: function () {
					this.backdrop = true;
					return this.show.apply(this, arguments);
				},


				/** 关闭浮层 */
				close: function (result) {

					if (!this.destroyed && this.open) {

						if (result !== undefined) {
							this.returnValue = result;
						}

						this.__popup.hide().removeClass(this.className + '-show');
						this.__backdrop.hide();
						this.open = false;
						this.blur();// 恢复焦点，照顾键盘操作的用户
						this.__dispatchEvent('close');
					}

					return this;
				},


				/** 销毁浮层 */
				remove: function () {

					if (this.destroyed) {
						return this;
					}

					this.__dispatchEvent('beforeremove');

					if (Popup.current === this) {
						Popup.current = null;
					}


					// 从 DOM 中移除节点
					var $popup = this.__popup.find('.popup-dialog');
					if($popup.length > 0){
						$popup.hide().appendTo('body');
					}
					this.__popup.remove();
					this.__backdrop.remove();
					this.__mask.remove();


					if (!_isIE6) {
						$(window).off('resize', this.reset);
					}


					this.__dispatchEvent('remove');

					for (var i in this) {
						delete this[i];
					}

					return this;
				},


				/** 重置位置 */
				reset: function () {

					var elem = this.follow;

					if (elem) {
						this.__follow(elem);
					} else {
						this.__center();
					}

					this.__dispatchEvent('reset');

					return this;
				},


				/** 让浮层获取焦点 */
				focus: function () {

					var node = this.node;
					var popup = this.__popup;
					var current = Popup.current;
					var index = this.zIndex = Popup.zIndex ++;

					if (current && current !== this) {
						current.blur(false);
					}

					// 检查焦点是否在浮层里面
					if (!$.contains(node, this.__getActive())) {
						var autofocus = popup.find('[autofocus]')[0];

						if (!this._autofocus && autofocus) {
							this._autofocus = true;
						} else {
							autofocus = node;
						}

						this.__focus(autofocus);
					}

					// 设置叠加高度
					popup.css('zIndex', index);
					//this.__backdrop.css('zIndex', index);

					Popup.current = this;
					popup.addClass(this.className + '-focus');

					this.__dispatchEvent('focus');

					return this;
				},


				/** 让浮层失去焦点。将焦点退还给之前的元素，照顾视力障碍用户 */
				blur: function () {

					var activeElement = this.__activeElement;
					var isBlur = arguments[0];


					if (isBlur !== false) {
						this.__focus(activeElement);
					}

					this._autofocus = false;
					this.__popup.removeClass(this.className + '-focus');
					this.__dispatchEvent('blur');

					return this;
				},


				/**
				 * 添加事件
				 * @param   {String}    事件类型
				 * @param   {Function}  监听函数
				 */
				addEventListener: function (type, callback) {
					this.__getEventListener(type).push(callback);
					return this;
				},


				/**
				 * 删除事件
				 * @param   {String}    事件类型
				 * @param   {Function}  监听函数
				 */
				removeEventListener: function (type, callback) {
					var listeners = this.__getEventListener(type);
					for (var i = 0; i < listeners.length; i ++) {
						if (callback === listeners[i]) {
							listeners.splice(i--, 1);
						}
					}
					return this;
				},


				// 获取事件缓存
				__getEventListener: function (type) {
					var listener = this.__listener;
					if (!listener) {
						listener = this.__listener = {};
					}
					if (!listener[type]) {
						listener[type] = [];
					}
					return listener[type];
				},


				// 派发事件
				__dispatchEvent: function (type) {
					var listeners = this.__getEventListener(type);

					if (this['on' + type]) {
						this['on' + type]();
					}

					for (var i = 0; i < listeners.length; i ++) {
						listeners[i].call(this);
					}
				},


				// 对元素安全聚焦
				__focus: function (elem) {
					// 防止 iframe 跨域无权限报错
					// 防止 IE 不可见元素报错
					try {
						// ie11 bug: iframe 页面点击会跳到顶部
						if (this.autofocus && !/^iframe$/i.test(elem.nodeName)) {
							elem.focus();
						}
					} catch (e) {}
				},


				// 获取当前焦点的元素
				__getActive: function () {
					try {// try: ie8~9, iframe #26
						var activeElement = document.activeElement;
						var msgDocument = activeElement.msgDocument;
						var elem = msgDocument && msgDocument.activeElement || activeElement;
						return elem;
					} catch (e) {}
				},


				// 居中浮层
				__center: function () {

					var popup = this.__popup;
					var $window = $(window);
					var $document = $(document);
					var fixed = this.fixed;
					var dl = fixed ? 0 : $document.scrollLeft();
					var dt = fixed ? 0 : $document.scrollTop();
					var ww = $window.width();
					var wh = $window.height();
					var ow = popup.width();
					var oh = popup.height();
					var left = (ww - ow) / 2 + dl;
					var top = (wh - oh) * 382 / 1000 + dt;// 黄金比例
					var style = popup[0].style;


					style.left = Math.max(parseInt(left), dl) + 'px';
					style.top = Math.max(parseInt(top), dt) + 'px';
				},


				// 指定位置 @param    {HTMLElement, Event}  anchor
				__follow: function (anchor) {

					var $elem = anchor.parentNode && $(anchor);
					var popup = this.__popup;


					if (this.__followSkin) {
						popup.removeClass(this.__followSkin);
					}


					// 隐藏元素不可用
					if ($elem) {
						var o = $elem.offset();
						if (o.left * o.top < 0) {
							return this.__center();
						}
					}

					var that = this;
					var fixed = this.fixed;

					var $window = $(window);
					var $document = $(document);
					var winWidth = $window.width();
					var winHeight = $window.height();
					var docLeft =  $document.scrollLeft();
					var docTop = $document.scrollTop();


					var popupWidth = popup.width();
					var popupHeight = popup.height();
					var width = $elem ? $elem.outerWidth() : 0;
					var height = $elem ? $elem.outerHeight() : 0;
					var offset = this.__offset(anchor);
					var x = offset.left;
					var y = offset.top;
					var left =  fixed ? x - docLeft : x;
					var top = fixed ? y - docTop : y;


					var minLeft = fixed ? 0 : docLeft;
					var minTop = fixed ? 0 : docTop;
					var maxLeft = minLeft + winWidth - popupWidth;
					var maxTop = minTop + winHeight - popupHeight;


					var css = {};
					var align = this.align.split(' ');
					var className = this.className + '-';
					var reverse = {top: 'bottom', bottom: 'top', left: 'right', right: 'left'};
					var name = {top: 'top', bottom: 'top', left: 'left', right: 'left'};


					var temp = [{
						top: top - popupHeight,
						bottom: top + height,
						left: left - popupWidth,
						right: left + width
					}, {
						top: top,
						bottom: top - popupHeight + height,
						left: left,
						right: left - popupWidth + width
					}];


					var center = {
						left: left + width / 2 - popupWidth / 2,
						top: top + height / 2 - popupHeight / 2
					};


					var range = {
						left: [minLeft, maxLeft],
						top: [minTop, maxTop]
					};


					// 超出可视区域重新适应位置
					$.each(align, function (i, val) {

						// 超出右或下边界：使用左或者上边对齐
						if (temp[i][val] > range[name[val]][1]) {
							val = align[i] = reverse[val];
						}

						// 超出左或右边界：使用右或者下边对齐
						if (temp[i][val] < range[name[val]][0]) {
							align[i] = reverse[val];
						}

					});


					// 一个参数的情况
					if (!align[1]) {
						name[align[1]] = name[align[0]] === 'left' ? 'top' : 'left';
						temp[1][align[1]] = center[name[align[1]]];
					}


					//添加follow的css, 为了给css使用
					className += align.join('-') + ' '+ this.className+ '-follow';

					that.__followSkin = className;


					if ($elem) {
						popup.addClass(className);
					}


					css[name[align[0]]] = parseInt(temp[0][align[0]]);
					css[name[align[1]]] = parseInt(temp[1][align[1]]);
					popup.css(css);

				},


				// 获取元素相对于页面的位置（包括iframe内的元素）
				// 暂时不支持两层以上的 iframe 套嵌
				__offset: function (anchor) {

					var isNode = anchor.parentNode;
					var offset = isNode ? $(anchor).offset() : {
						left: anchor.pageX,
						top: anchor.pageY
					};


					anchor = isNode ? anchor : anchor.target;
					var ownerDocument = anchor.ownerDocument;
					var defaultView = ownerDocument.defaultView || ownerDocument.parentWindow;

					if (defaultView == window) {// IE <= 8 只能使用两个等于号
						return offset;
					}

					// {Element: Ifarme}
					var frameElement = defaultView.frameElement;
					var $ownerDocument = $(ownerDocument);
					var docLeft =  $ownerDocument.scrollLeft();
					var docTop = $ownerDocument.scrollTop();
					var frameOffset = $(frameElement).offset();
					var frameLeft = frameOffset.left;
					var frameTop = frameOffset.top;

					return {
						left: offset.left + frameLeft - docLeft,
						top: offset.top + frameTop - docTop
					};
				}

			});

			/** 当前叠加高度 */
			Popup.zIndex = 1024;

			/** 顶层浮层的实例 */
			Popup.current = null;

			return Popup;

		})(),

		// dialog - 默认配置
		defaults = {

			/* -----已注释的配置继承自 popup.js，仍可以再这里重新定义它----- */

			// 对齐方式
			//align: 'bottom left',

			// 是否固定定位
			//fixed: false,

			// 对话框叠加高度值(重要：此值不能超过浏览器最大限制)
			//zIndex: 1024,

			// 设置遮罩背景颜色
			backdropBackground: '#000',

			// 设置遮罩透明度
			backdropOpacity: 0.7,

			// 消息内容
			msg: '<span class="ui-dialog-loading">Loading..</span>',

			// 标题
			title: '操作提示',

			// 对话框状态栏区域 HTML 代码
			statusbar: '',

			// 自定义按钮
			button: null,

			// 确定按钮回调函数
			okHandler : null,

			// 取消按钮回调函数
			clHandler : null,

			//远程地址
			url : '',

			//load形式加载远程地址
			load : false,

			//frame形式加载远程地址
			frame : false,

			// 确定按钮文本
			btnok: '确定',

			// 取消按钮文本
			btncl: '取消',

			//综合回调,参数为true或false
			callback : null,

			cancelDisplay: true,

			// 内容宽度
			width: '',

			// 内容高度
			height: '',

			// 内容与边界填充距离
			padding: '',

			// 对话框自定义 className
			skin: '',

			// 是否支持快捷关闭（点击遮罩层自动关闭）
			quickClose: false,

			// css 文件路径，留空则不会使用 js 自动加载样式
			// 注意：css 只允许加载一个
			cssUri: '',

			//模态
			backdrop : true,

			//限时隐藏
			timeHidden : 0,

			// 模板（使用 table 解决 IE7 宽度自适应的 BUG）
			// js 使用 i="***" 属性识别结构，其余的均可自定义
			innerHTML:
			'<div i="dialog" class="ui-dialog">'
			+       '<div class="ui-dialog-arrow-a"></div>'
			+       '<div class="ui-dialog-arrow-b"></div>'
			+       '<table class="ui-dialog-grid">'
			+           '<tr>'
			+               '<td i="header" class="ui-dialog-header">'
			+                   '<button i="close" class="ui-dialog-close">&#215;</button>'
			+                   '<div i="title" class="ui-dialog-title"></div>'
			+               '</td>'
			+           '</tr>'
			+           '<tr>'
			+               '<td i="body" class="ui-dialog-body">'
			+                   '<div i="msg" class="ui-dialog-msg"></div>'
			+               '</td>'
			+           '</tr>'
			+           '<tr>'
			+               '<td i="footer" class="ui-dialog-footer">'
			+                   '<div i="statusbar" class="ui-dialog-statusbar"></div>'
			+                   '<div i="button" class="ui-dialog-button"></div>'
			+               '</td>'
			+           '</tr>'
			+       '</table>'
			+'</div>'

		},

		/*!
		 * dialog
		 */
		dialog = (function () {
			var css = defaults.cssUri;
			// css loader: RequireJS & SeaJS
			if (css) {
				var fn = require[require.toUrl ? 'toUrl' : 'resolve'];
				if (fn) {
					css = fn(css);
					css = '<link rel="stylesheet" href="' + css + '" />';
					if ($('base')[0]) {
						$('base').before(css);
					} else {
						$('head').append(css);
					}
				}
			}


			var _count = 0;
			var _expando = new Date() - 0; // Date.now()
			var _isIE6 = !('minWidth' in $('html')[0].style);
			var _isMobile = 'createTouch' in document && !('onmousemove' in document)
				|| /(iPhone|iPad|iPod)/i.test(navigator.userAgent);
			var _isFixed = !_isIE6 && !_isMobile;


			var artDialog = function (options, ok, cancel) {

				var originalOptions = options = options || {};


				if (typeof options === 'string' || options.nodeType === 1) {

					options = {msg: options, fixed: !_isMobile};
				}


				options = $.extend(true, {}, artDialog.defaults, options);
				options.original = originalOptions;

				var id = options.id = options.id || _expando + _count;
				var api = artDialog.get(id);


				// 如果存在同名的对话框对象，则直接返回
				if (api) {
					return api.focus();
				}


				// 目前主流移动设备对fixed支持不好，禁用此特性
				if (!_isFixed) {
					options.fixed = false;
				}


				// 快捷关闭支持：点击对话框外快速关闭对话框
				if (options.quickClose) {
					options.backdrop = true;
					options.backdropOpacity = 0;
				}


				// 按钮组
				if (!$.isArray(options.button)) {
					options.button = [];
				}


				// 确定按钮
				if (ok !== undefined) {
					options.okHandler = ok;
				}

				if (options.okHandler && options.btnok !== false) {
					options.button.push({
						id: 'ok',
						value: options.btnok,
						callback: options.okHandler,
						close: options.okClose,
						autofocus: true,
						handler : function(){typeof options.callback == 'function' ? options.callback(true) : false}
					});
				}


				// 取消按钮
				if (cancel !== undefined) {
					options.clHandler = cancel;
				}

				if (options.clHandler && options.btncl !== false) {
					options.button.push({
						id: 'cancel',
						value: options.btncl,
						close: true,
						callback: options.clHandler,
						display: options.cancelDisplay,
						handler : function(){typeof options.callback == 'function' ? options.callback(false) : false}
					});
				}


				return artDialog.list[id] = new artDialog.create(options);
			};

			var popup = function () {};
			popup.prototype = Popup.prototype;
			var prototype = artDialog.prototype = new popup();

			artDialog.create = function (options) {
				var that = this;

				//长度与宽度限制
				if(!options.width && (options.load || options.frame || options.dialog)){
					var width = $(window).width() * 0.8;
					options.width = width;
				}
				if(!options.height && (options.load || options.frame || options.dialog)){
					var height = $(window).height() * 0.8;
					height = height - 120 < 100 ? 50 : height - 100;
					options.height = height;
				}

				$.extend(this, new Popup());

				var originalOptions = options.original;
				var $popup = $(this.node).html(options.innerHTML);
				var $backdrop = $(this.backdrop);

				this.options = options;
				this._popup = $popup;


				$.each(options, function (name, value) {
					if (typeof that[name] === 'function') {
						that[name](value);
					} else {
						that[name] = value;
					}
				});

				if(options.url && typeof options.url == 'string'){
					var $dia = $(this.node), $container = $dia.find('.ui-dialog-msg');
					//远程加载load
					if(options.load){
						$container.empty().append('<div class="modal-load" style="width:100%;height:100%;overflow:auto"></div>');
						$container.find('.modal-load').load(options.url, function(){
							if(typeof options.completeFunc == 'function'){
								options.completeFunc({dialog : $dia});
							}
						});
					}
					//加载iframe
					else if(options.frame){
						$container.empty().append('<iframe src="' + options.url + '" frameborder="no" scrolling="auto" style="width:100%;height:100%"></iframe>');
						frameLoad($container.find('iframe').get(0), function(){
							if(typeof options.completeFunc == 'function'){
								options.completeFunc({dialog : $dia});
							}
						});
					}
				}else if(options.dialog){
					var $dia = $(this.node), $container = $dia.find('.ui-dialog-msg');
					$container.empty().append('<div class="modal-load" style="width:100%;height:100%;overflow:auto"></div>');
					if(options.dialog) {
						$container.find('.modal-load').append($(options.dialog).addClass('popup-dialog').show());
						if (typeof options.completeFunc == 'function') {
							options.completeFunc({dialog: $dia});
						}
					}
				}

				//框架监测
				function frameLoad(frame, fn){
					if(!frame){
						fn();
						return;
					}
					if(frame.readyState == "complete" || frame.readyState == 1){
						fn();
					}else{
						if (frame.attachEvent){
							frame.attachEvent("onload", function(){
								fn();
							});
						} else {
							frame.onload = function(){
								fn();
							};
						}
					}
				};

				// 更新 zIndex 全局配置
				if (options.zIndex) {
					Popup.zIndex = options.zIndex;
				}


				// 设置 ARIA 信息
				$popup.attr({
					'aria-labelledby': this._$('title')
						.attr('id', 'title:' + this.id).attr('id'),
					'aria-describedby': this._$('msg')
						.attr('id', 'msg:' + this.id).attr('id')
				});


				// 关闭按钮
				this._$('close')
					.css('display', this.cancel === false ? 'none' : '')
					.attr('title', this.btncl)
					.on('click', function (event) {
						that._trigger('cancel', true);
						event.preventDefault();
					});


				// 添加视觉参数
				this._$('dialog').addClass(this.skin);
				this._$('body').css('padding', this.padding);


				// 点击任意空白处关闭对话框
				if (options.quickClose) {
					$backdrop
						.on(
							'onmousedown' in document ? 'mousedown' : 'click',
							function () {
								that._trigger('cancel', true);
								return false;// 阻止抢夺焦点
							});
				}


				// 遮罩设置
				this.addEventListener('show', function () {
					$backdrop.css({
						opacity: 0,
						background: options.backdropBackground
					}).animate(
						{opacity: options.backdropOpacity}
						, 150);
				});


				// ESC 快捷键关闭对话框
				this._esc = function (event) {
					var target = event.target;
					var nodeName = target.nodeName;
					var rinput = /^input|textarea$/i;
					var isTop = Popup.current === that;
					var keyCode = event.keyCode;

					// 避免输入状态中 ESC 误操作关闭
					if (!isTop || rinput.test(nodeName) && target.type !== 'button') {
						return;
					}

					if (keyCode === 27) {
						that._trigger('cancel', true);
					}
				};

				//限时隐藏
				if(options.timeHidden){
					var timer;
					function hideDialog(){
						timer = setTimeout(function(){
							that.close();
						}, options.timeHidden);
					}

					$popup.mouseenter(function(){
						clearTimeout(timer);
					});

					$popup.mouseleave(function(){
						hideDialog();
					});

					hideDialog();

				}

				$(document).on('keydown', this._esc);
				this.addEventListener('remove', function () {
					$(document).off('keydown', this._esc);
					delete artDialog.list[this.id];
				});


				_count ++;

				artDialog.oncreate(this);

				return this;
			};


			artDialog.create.prototype = prototype;



			$.extend(prototype, {

				/**
				 * 显示对话框
				 * @name artDialog.prototype.show
				 * @param   {HTMLElement Object, Event Object}  指定位置（可选）
				 */

				/**
				 * 显示对话框（模态）
				 * @name artDialog.prototype.showModal
				 * @param   {HTMLElement Object, Event Object}  指定位置（可选）
				 */

				/**
				 * 关闭对话框
				 * @name artDialog.prototype.close
				 * @param   {String, Number}    返回值，可被 onclose 事件收取（可选）
				 */

				/**
				 * 销毁对话框
				 * @name artDialog.prototype.remove
				 */

				/**
				 * 重置对话框位置
				 * @name artDialog.prototype.reset
				 */

				/**
				 * 让对话框聚焦（同时置顶）
				 * @name artDialog.prototype.focus
				 */

				/**
				 * 让对话框失焦（同时置顶）
				 * @name artDialog.prototype.blur
				 */

				/**
				 * 添加事件
				 * @param   {String}    事件类型
				 * @param   {Function}  监听函数
				 * @name artDialog.prototype.addEventListener
				 */

				/**
				 * 删除事件
				 * @param   {String}    事件类型
				 * @param   {Function}  监听函数
				 * @name artDialog.prototype.removeEventListener
				 */

				/**
				 * 对话框显示事件，在 show()、showModal() 执行
				 * @name artDialog.prototype.onshow
				 * @event
				 */

				/**
				 * 关闭事件，在 close() 执行
				 * @name artDialog.prototype.onclose
				 * @event
				 */

				/**
				 * 销毁前事件，在 remove() 前执行
				 * @name artDialog.prototype.onbeforeremove
				 * @event
				 */

				/**
				 * 销毁事件，在 remove() 执行
				 * @name artDialog.prototype.onremove
				 * @event
				 */

				/**
				 * 重置事件，在 reset() 执行
				 * @name artDialog.prototype.onreset
				 * @event
				 */

				/**
				 * 焦点事件，在 foucs() 执行
				 * @name artDialog.prototype.onfocus
				 * @event
				 */

				/**
				 * 失焦事件，在 blur() 执行
				 * @name artDialog.prototype.onblur
				 * @event
				 */


				/**
				 * 设置内容
				 * @param    {String, HTMLElement}   内容
				 */
				msg: function (html) {

					var $msg = this._$('msg');

					// HTMLElement
					if (typeof html === 'object') {
						html = $(html);
						$msg.empty('').append(html.show());
						this.addEventListener('beforeremove', function () {
							$('body').append(html.hide());
						});
						// String
					} else {
						$msg.html(html);
					}

					return this.reset();
				},


				/**
				 * 设置标题
				 * @param    {String}   标题内容
				 */
				title: function (text) {
					this._$('title').text(text);
					this._$('header')[text ? 'show' : 'hide']();
					return this;
				},


				/** 设置宽度 */
				width: function (value) {
					this._$('msg').css('width', value);
					return this.reset();
				},


				/** 设置高度 */
				height: function (value) {
					this._$('msg').css('height', value);
					return this.reset();
				},


				/**
				 * 设置按钮组
				 * @param   {Array, String}
				 * Options: value, callback, autofocus, disabled
				 */
				button: function (args) {
					args = args || [];
					var that = this;
					var html = '';
					var number = 0;
					this.callbacks = {};


					if (typeof args === 'string') {
						html = args;
						number ++;
					} else {
						$.each(args, function (i, val) {

							var id = val.id = val.id || val.value;
							var style = '', handler = val.handler;
							that.callbacks[id] = val.callback;


							if (val.display === false) {
								style = ' style="display:none"';
							} else {
								number ++;
							}

							html +=
								'<button'
								+ ' type="button"'
								+ ' i-id="' + id + '"'
								+ style
								+ (val.disabled ? ' disabled' : '')
								+ (val.close ? ' data-close-dia="true"' : '')
								+ (val.autofocus ? ' autofocus class="ui-dialog-autofocus"' : '')
								+ '>'
								+   val.value
								+ '</button>';

							that._$('button')
								.on('click', '[i-id=' + id +']', function (event) {
									var $this = $(this), b = !!$this.attr('data-close-dia') ? true : false;
									if (!$this.attr('disabled')) {// IE BUG
										that._trigger(id, b);
									}
									if(handler) handler();
									event.preventDefault();
								});

						});
					}

					this._$('button').html(html);
					this._$('footer')[number ? 'show' : 'hide']();

					return this;
				},


				statusbar: function (html) {
					this._$('statusbar')
						.html(html)[html ? 'show' : 'hide']();

					return this;
				},


				_$: function (i) {
					return this._popup.find('[i=' + i + ']');
				},


				// 触发按钮回调函数
				_trigger: function (id, close) {
					var fn = this.callbacks[id], result;
					result = typeof fn !== 'function' || fn.call(this.node);
					if(close === true) this.close().remove();
					return result;
				}

			});

			artDialog.oncreate = $.noop;

			/** 获取最顶层的对话框API */
			artDialog.getCurrent = function () {
				return Popup.current;
			};



			/**
			 * 根据 ID 获取某对话框 API
			 * @param    {String}    对话框 ID
			 * @return   {Object}    对话框 API (实例)
			 */
			artDialog.get = function (id) {
				return id === undefined
					? artDialog.list
					: artDialog.list[id];
			};

			artDialog.list = {};

			/**
			 * 默认配置
			 */
			artDialog.defaults = defaults;

			return artDialog;

		})();

	return dialoger;

});